#include "StdAfx.h"
#include "lua_manager.h"
#include <sstream>
#include "AppAPI.h"

const char * get_exe_path()
{
#ifdef WIN32
    static char szPath[MAX_PATH];
    static bool bFirstTime = true;

    if(bFirstTime)
    {
        bFirstTime = false;
        GetModuleFileName(NULL, szPath, sizeof(szPath));
        char *p = strrchr(szPath, '\\');
        *p = '\0';
    }

    return szPath;
#else
    return ".";
#endif
}

lua_manager::lua_manager(void) : _state(NULL)
{
}

lua_manager::~lua_manager(void)
{
    if (_state)
    {
        lua_close(_state);
        _state = NULL;
    }
}

bool lua_manager::init()
{
    _state = lua_open();
    luaL_openlibs(_state);
    luabind::open(_state);
    std::string configure_file = get_exe_path();
    configure_file += "\\script\\configure.lua";
    if (!_load_file(configure_file.c_str()))
        return false;
    using namespace luabind;
    module(_state)
    [
#include "AppAPI.inc"
    ];

    return true;
}

bool lua_manager::_load_file(const char * path)
{
    if( luaL_dofile(_state, path) )
    {
        _last_error = lua_tostring(_state, -1);
        return false;
    }
    return true;
}

bool lua_manager::load_file(const char * filename)
{
    std::ostringstream command;
    command << "package.loaded[\"" << filename << "\"]=nil;" 
            << "require \"" << filename << '\"';
    int error = luaL_loadbuffer(_state, command.str().c_str(), command.str().length(),
        "line") || lua_pcall(_state, 0, 0, 0);
    if (error) {
        _last_error = lua_tostring(_state, -1);
        lua_pop(_state, 1);/* pop error message from the stack */
        return false;
    }
    return true;
}

void lua_manager::add_path(const char *path)
{
    luabind::call_function<void>(_state, "addpath", path);
}

